from rest_framework import serializers
from article.models import Article,Tag,Catagory


class TagSerializer(serializers.ModelSerializer):
    def check_tag_obj_exists(self,validated_data):
        tag = validated_data.get("tag")
        if Tag.objects.filter(tag=tag).exists():
            raise serializers.ValidationError("该标签已经存在")
    
    def create(self, validated_data):
        self.check_tag_obj_exists(validated_data)
        return super().create(validated_data)
    
    def update(self, instance, validated_data):
        self.check_tag_obj_exists(validated_data)
        return super().update(instance, validated_data)
    class Meta:
        model = Tag
        fields = "__all__"
        

class CatagorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Catagory
        fields = "__all__"

class ArticleSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.IntegerField(read_only=True)
    catagory = CatagorySerializer(read_only=True)
    tags = serializers.SlugRelatedField(
        queryset=Tag.objects.all(),many=True,required=False,slug_field='tag'
    )
    content_html = serializers.SerializerMethodField() #渲染后的内容
    toc_html = serializers.SerializerMethodField() #渲染后的目录
    
    def get_content_html(self, obj):
        return obj.get_md()[0]

    def get_toc_html(self, obj):
        return obj.get_md()[1]
    
    class Meta:
        model = Article
        fields = "__all__"
        read_only_fields = ["created_time"]
        extra_kwargs = {'content': {'write_only': True}}